package com.fr.lintcode;

import org.junit.Test;

/**
*作者：furong
*日期：2017年2月23日
*时间：下午3:57:10
*/
public class Q412 {
    /**
     * 错误
     * @param ratings Children's ratings
     * @return the minimum candies you must give
     */
    public int candy(int[] ratings) {
        if (ratings == null || ratings.length <= 0) {
            return 0;
        }
        int length = ratings.length;
        if (length == 1) {
            return 1;
        }
        int dp[] = new int[length];
        dp[0] = find(ratings);
        int sum = dp[0];
        for (int i = 1; i < length; i++) {
            if (ratings[i] > ratings[i - 1]) {
                dp[i] = dp[i - 1] + 1;
            } else if (ratings[i] == ratings[i - 1]) {
                if (findLess(ratings, i + 1)) {
                    dp[i] = dp[i - 1];
                } else {
                    dp[i] = dp[i - 1] - 1 > 0 ? dp[i - 1] - 1 : 1;
                }
            } else {
                dp[i] = dp[i - 1] - 1 > 0 ? dp[i - 1] - 1 : 1;
            }
            sum += dp[i];
        }
        if (ratings[0] <= ratings[1]) {
            sum = sum - dp[0] + 1;
        }
        return sum;
    }

    private int find(int[] ratings) {
        int count = 1;
        for (int i = 1; i < ratings.length; i++) {
            if (ratings[i] < ratings[i - 1]) {
                count++;
            } else if (ratings[i] == ratings[i - 1]) {

            } else {
                break;
            }
        }
        return count;
    }

    private boolean findLess(int[] ratings, int index) {
        for (int i = index; i < ratings.length; i++) {
            if (ratings[i] < ratings[i - 1]) {
                return true;
            } else if (ratings[i] == ratings[i - 1]) {

            } else {
                return false;
            }
        }
        return false;
    }

    @Test
    public void testA() {
        int[] ratings = { 1, 2, 1, 1, 0 };
        System.out.println(candy(ratings));
    }
}
